package com.wzs.util;

import java.io.IOException;
import java.sql.*;
import java.util.Properties;

/**
 * @author miaomiao
 * @version 1.0.0
 * @ClassName JUtil.java
 * @Description TODO
 * @createTime 2021-06-19- 23:30:00
 */
public class JUtil {

    Connection conn = null;

    private JUtil() {
    }

    private static final JUtil instance = new JUtil();

    public static JUtil getInstance() {
        return instance;
    }

    public Connection getConnection() {

        Properties prop = new Properties();
        try {
            prop.load(JdbcUtil.class.getClassLoader().getResourceAsStream("jdbc.properties"));
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        String driver = prop.getProperty("driver");
        String url = prop.getProperty("url");
        String user = prop.getProperty("username");
        String password = prop.getProperty("password");
        try {
            if (driver == null) {
                driver = prop.getProperty("driver");
            }
            Class.forName(driver);
            if (null == conn || conn.isClosed()) {
                conn = DriverManager.getConnection(url, user, password);
            }
            System.out.println("Mysql连接成功");
        } catch (SQLException e) {
            e.printStackTrace();
            System.out.println("sql exception" + e.getMessage());
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            System.out.println("Driver class not found" + e.getMessage());
        }
        return conn;
    }

    public static void close(Connection conn, Statement pstm, ResultSet rs) {

        try {
            if (rs != null) {
                rs.close();
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            try {
                if (pstm != null) {
                    pstm.close();
                }
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            } finally {
                try {
                    if (conn != null) {
                        conn.close();
                    }
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
        }
    }


}
